package com.zry.simpleBlog.upload;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.zry.simpleBlog.comment.enums.RespBeanEnum;
import com.zry.simpleBlog.comment.exception.BusinessException;
import com.zry.simpleBlog.comment.utils.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

/**
 */
@Service
public class QiniuServiceImpl implements QiniuService {

    @Resource
    private UploadManager uploadManager;

    @Resource
    private Auth auth;

    @Value("${qiniu.filePath}")
    private String filePath;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public String uploadAvatar(MultipartFile file) throws IOException {
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        // 检查图片类型
        if (!FileUtil.isFileAllowed(suffix)) {
            throw new BusinessException(RespBeanEnum.FILE_TYPE_NOT_SUPPORTED);
        }
        InputStream inputStream = file.getInputStream();
        // 存储路径
        String key = filePath + file.getOriginalFilename();
        // 上传图片
        DefaultPutRet putRet;
        try {
            Response response = this.uploadManager.put(inputStream, key, this.getUploadToken(), null, null);
            int retry = 0;
            while (response.needRetry() && retry < 3) {
                response = this.uploadManager.put(inputStream, key, this.getUploadToken(), null, null);
                retry++;
            }
            //解析结果
            putRet = objectMapper.readValue(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException e) {
            throw new BusinessException(400, "七牛云服务异常：" + e.error());
        }
        return putRet.key;
    }

    /**
     * 获取上传凭证
     *
     * @return
     */
    private String getUploadToken() {
        StringMap PUT_POLICY = new StringMap();
        if (PUT_POLICY.size() == 0) {
            PUT_POLICY.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(hash)\"}");
        }
        return this.auth.uploadToken(bucket, null, 3600L, PUT_POLICY);
    }
}
